<template>
  <div>
    <Card :bordered="false" dis-hover class="ivu-mt">
      <Form :label-width="90">
        <FormItem label="分类：">
          <TagSelect
            ref="labelList"
            :expandable="status"
            :class="{ labelList: !status }"
            v-model="type"
            @on-change="onSearch"
          >
            <TagSelectOption
              v-for="(part, index) in headSelectedList"
              :key="'part-' + index"
              :name="part.id"
              >{{ part.name }}</TagSelectOption
            >
          </TagSelect>
        </FormItem>
        <Divider dashed />
        <Row type="flex">
          <Col>
            <FormItem label="排序：">
              <RadioGroup v-model="order" @on-change="onSearch">
                <Radio label="1">顺序时间</Radio>
                <Radio label="0">倒序时间</Radio>
              </RadioGroup>
            </FormItem>
          </Col>
          <Col span="13" class="frListTime">
            <FormItem label="治疗日期：">
              <Select
                v-model="modelTime"
                @on-change="selectTimeImage"
                filterable
                multiple
                :max-tag-count="3"
              >
                <Option
                  v-for="(item, index) in orderTime"
                  :value="item"
                  :key="'item' + index"
                  >{{ item }}</Option
                >
              </Select>
            </FormItem>
          </Col>
        </Row>
      </Form>
    </Card>
    <Row v-if="edit" :gutter="24" class="ivu-mt images">
      <CheckboxGroup v-model="delSel">
        <Col
          :xl="compact ? 12 : 6"
          :lg="compact ? 12 : 8"
          :md="12"
          :sm="12"
          :xs="24"
          v-for="(items, index) in projectList"
          :key="index"
          class="ivu-mb"
        >
          <Card
            :bordered="bordered"
            dis-hover
            :padding="0"
            class="search-search-projects-item"
          >
            <Checkbox
              :label="items.id"
              class="checkSelBot"
              :class="edit ? '' : 'checkSel'"
            >
              <div class="imgArea">
                <img
                  @error="imgError(items)"
                  :src="
                    items.img_thumb_url ? items.img_thumb_url : items.img_url
                  "
                  :data-source="
                    items.img_url ? items.img_url : items.img_thumb_url
                  "
                  class="search-search-projects-item-cover"
                />
              </div>
            </Checkbox>
            <div class="ivu-p-8">
              <div class="search-search-projects-item-extra">
                <span style="line-height: 30px">
                  {{ items.created_at_str }}
                </span>
                <span class="ivu-fr">
                  <Select v-model="partSel[index].body_parts_id">
                    <Option
                      v-for="item in bodyList"
                      :value="item.id"
                      :key="item.id"
                      >{{ item.name }}</Option
                    >
                  </Select>
                </span>
              </div>
            </div>
          </Card>
        </Col>
      </CheckboxGroup>
    </Row>
    <Row
      v-else
      :gutter="24"
      class="ivu-mt images"
      v-viewer="{ movable: false }"
    >
      <Col
        :xl="compact ? 12 : 6"
        :lg="compact ? 12 : 8"
        :md="12"
        :sm="12"
        :xs="24"
        v-for="(items, index) in projectList"
        :key="index"
        class="ivu-mb"
      >
        <Card
          :bordered="bordered"
          dis-hover
          :padding="0"
          class="search-search-projects-item"
        >
          <div class="imgArea">
            <img
              @error="imgError(items)"
              :src="items.img_thumb_url ? items.img_thumb_url : items.img_url"
              :data-source="items.img_url ? items.img_url : items.img_thumb_url"
              class="search-search-projects-item-cover"
            />
          </div>
          <div class="ivu-p-8">
            <div class="search-search-projects-item-extra ivu-mt-8 ivu-pb-8">
              <span>
                {{ items.created_at_str }}
              </span>
              <span class="ivu-fr">
                {{ items.body_parts_name }}
              </span>
            </div>
          </div>
        </Card>
      </Col>
    </Row>
    <div class="ivu-text-center only-bottom" v-if="empty">
      <span v-if="projectList.length === 0">暂无治疗图片</span>
      <span v-else>——图片全部加载完毕——</span>
    </div>
    <div class="ivu-text-center only-bottom" v-else>
      <Button v-if="!edit" type="primary" @click="getMoreData">加载更多</Button>
    </div>
    <FooterToolbar v-if="edit">
      <a
        class="ivu-btn ivu-mr-8 ivu-btn-warning ivu-btn-large v-mt-20"
        :href="`baiyou://${patientCardId}`"
        type="warning"
        size="large"
        >图片本地文件夹</a
      >
      <Button @click="resetPartSel" class="v-mt-20" size="large">取消</Button>
      <Button @click="delPart" type="error" class="v-mt-20" size="large"
        >删除</Button
      >
      <Button @click="submitSave" type="primary" class="v-mt-20" size="large"
        >保存</Button
      >
    </FooterToolbar>
    <FooterToolbar v-else>
      <Button @click="edit = true" type="primary" class="v-mt-20" size="large"
        >编辑</Button
      >
    </FooterToolbar>
  </div>
</template>
<script>
import {
  PatientClinicImgList,
  PatientClinicImgEdit,
  PatientClinicImgDelete,
} from "@api/patient";

export default {
  name: "detailed-Images",
  props: {
    compact: {
      type: Boolean,
      default: false,
    },
    bordered: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      status: false,
      loading: false,
      partSel: [],
      type: [],
      order: "0",
      modelTime: [],
      orderTime: [],
      projectList: [],
      single: false,
      bodyList: [],
      // 备注： 组件bug, 添加初始占位值
      headSelectedList: [{ id: "0", name: "" }],
      patientCardId: "",
      edit: false,
      delSel: [],
      errorUserPhoto:
        "https://dev-file.iviewui.com/WLXm7gp1EbLDtvVQgkeQeyq5OtDm00Jd/middle",
      page: 1,
      pageSize: 8,
      empty: false,
      timer: false,
      screenWidth: 0,
      state: true,
    };
  },
  methods: {
    imgError(item) {
      item.img_url = this.errorUserPhoto;
    },
    initResize() {
      const that = this;
      window.onresize = () => {
        if (this.state) {
          this.state = false;
          that.labelList();
          setTimeout(() => {
            that.state = true;
          }, 300);
        }
      };
    },
    onLoad() {
      const that = this;
      window.onresize = () => {
        return (() => {
          window.screenWidth = document.body.clientWidth;
          that.screenWidth = window.screenWidth;
          if (that.screenWidth < 1200) {
            that.pageSize = 6;
          } else {
            that.pageSize = 8;
          }
        })();
      };
    },
    // 根据时间查询图片
    selectTimeImage() {
      this.status = false;
      this.page = 1;
      this.empty = false;
      this.projectList = [];
      this.patientClinicImgList();
    },
    getData(id) {
      this.patientCardId = id;
      this.projectList = [];
      this.orderTime = [];
      this.status = false;
      this.page = 1;
      this.empty = false;
      this.patientClinicImgList();
      this.initResize();
    },
    getMoreData() {
      this.page = this.page + 1;
      this.patientClinicImgList();
    },
    patientClinicImgList() {
      const params = {
        patient_card_id: this.patientCardId,
        sort_created_at_type: this.order,
        page: this.page,
        pageSize: this.pageSize,
        img_date: this.modelTime.join(","),
      };
      if (this.type.length !== this.bodyList.length) {
        params.body_parts_id = this.type.join(",");
      }
      PatientClinicImgList(params)
        .then((res) => {
          this.bodyList = res.condition.body_parts_list;
          this.headSelectedList = res.condition.select_body_parts_list;
          this.projectList = this.projectList.concat(res.list);
          this.orderTime = res.condition.date_list || [];
          this.partSel = this.filterSel(this.projectList);
          if (this.page * this.pageSize >= res.total) {
            this.empty = true;
          }
          this.loading = false;
          this.labelList();
        })
        .catch(() => {});
    },
    // 判断标签个数
    labelList() {
      this.status = false;
      this.$nextTick(() => {
        const height =
          this.$refs.labelList && this.$refs.labelList.$el.offsetHeight;
        if (height > 32) this.status = true;
        else this.status = false;
      });
    },
    filterSel(arr) {
      let reArr = [];
      if (arr && arr.length > 0) {
        arr.forEach((items) => {
          const reItem = {
            id: items.id,
            body_parts_id: items.body_parts_id,
          };
          reArr.push(reItem);
        });
      }
      return reArr;
    },
    resetPartSel() {
      this.partSel = this.filterSel(this.projectList);
      this.delSel = [];
      this.edit = false;
    },
    delPart() {
      const param = {
        ids: this.delSel.join(","),
      };
      const length = this.delSel.length;
      this.$Modal.confirm({
        title: "删除治疗图片",
        content: "确定删除这" + length + "张图片?",
        onOk: () => {
          this.deleteSubmit(param);
        },
        onCancel: () => {},
      });
    },
    deleteSubmit(param) {
      PatientClinicImgDelete(param)
        .then((res) => {
          this.$Message.success(" 删除图片成功");
          this.loading = false;
          this.edit = false;
          this.projectList = [];
          this.patientClinicImgList();
        })
        .catch(() => {});
    },
    submitSave() {
      const params = {
        patient_card_id: parseInt(this.patientCardId),
        clinic_imgs: JSON.stringify(this.partSel),
      };
      this.loading = true;
      PatientClinicImgEdit(params)
        .then((res) => {
          this.$Message.success("提交保存成功！");
          this.loading = false;
          this.onSearch();
        })
        .catch(() => {
          this.loading = false;
        });
    },
    onSearch() {
      this.edit = false;
      this.page = 1;
      this.empty = false;
      this.projectList = [];
      this.patientClinicImgList();
    },
  },
  watch: {
    screenWidth(val) {
      // 为了避免频繁触发resize函数导致页面卡顿，使用定时器
      if (!this.timer) {
        // 一旦监听到的screenWidth值改变，就将其重新赋给data里的screenWidth
        this.screenWidth = val;
        this.timer = true;
        let that = this;
        setTimeout(function() {
          // 打印screenWidth变化的值
          that.timer = false;
        }, 400);
      }
    },
  },
  destroyed() {
    window.removeEventListener("onresize", (e) => this.labelList());
  },
};
</script>
<style lang="less" scoped>
.only-bottom {
  padding-bottom: 40px;
}
.search-search-projects {
  &-item {
    width: 258px;
    .imgArea {
      width: 256px;
      height: 160px;
      img {
        width: 100%;
        height: 100%;
        object-fit: cover;
      }
    }
    .checkSel {
      .ivu-checkbox {
        display: none;
      }
    }
    .ivu-checkbox-wrapper {
      margin-right: 0;
      .ivu-checkbox {
        position: absolute;
        top: 4px;
        left: 4px;
        z-index: 999;
      }
    }
    &-cover {
      width: 100%;
      border-radius: 4px 4px 0 0;
    }
    &-desc {
      display: -webkit-box;
      height: 40px;
      -webkit-line-clamp: 2;
      -webkit-box-orient: vertical;
      overflow: hidden;
    }
    &-extra {
      span {
        display: inline-block;
        color: #808695;
        vertical-align: middle;
        margin-left: 10px;
      }
    }
  }
}
.labelList {
  max-height: none;
}
.frListTime {
  margin-left: auto;
}
.checkSelBot /deep/.ivu-checkbox {
  position: absolute;
  left: 5px;
  bottom: 55px;
}
</style>
